package com.mk.seckill.utils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
/**
 * @Author hhwu
 * @Description //TODO JSON工具类
 * @Date 10:24 2022/6/13
 **/
public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String object2JsonStr(Object obj) {
        /**
         * @Author hhwu
         * @Description //TODO 将对象转换成json字符串
         * @Date 10:24 2022/6/13
         * @Param [obj]
         * @return java.lang.String
         **/
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            //打印异常信息
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T jsonStr2Object(String jsonStr, Class<T> clazz) {
        /**
         * @Author hhwu
         * @Description //TODO 将字符串转换为对象
         * @Date 10:24 2022/6/13
         * @Param [jsonStr, clazz]
         * @return T
         **/
        try {
            return objectMapper.readValue(jsonStr.getBytes("UTF-8"), clazz);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> List<T> jsonToList(String jsonStr, Class<T> beanType) {
        /**
         * @Author hhwu
         * @Description //TODO 将json数据转换成pojo对象list
         * @Date 10:24 2022/6/13
         * @Param [jsonStr, beanType]
         * @return java.util.List<T>
         **/
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = objectMapper.readValue(jsonStr, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
